﻿using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
/** SerialPort 参数配置集合
 */
namespace WpfComm.Models
{
    public class SerialPortParameter
    {
        //串口号
        public List<string> PortName { get; set; }
        //校验位        
        public List<string> Parity { get; set; }
        //波特率        
        public List<int> BaudRate { get; set; }
        //数据位
        public List<int> DataBits { get; set; }
        //停止位
        public List<string> StopBits { get; set; }

        /// <summary>
        /// 初始化
        /// </summary>
        public SerialPortParameter()
        {
            //串口号
            this.PortName = new List<string>();
            //校验位        
            this.Parity = new List<string>();
            //波特率        
            //数据位
            //波特率        
            this.BaudRate = new List<int>
            {
                9600,115200,57600,43000,38400,19200,4800
            };
            //数据位
            this.DataBits = new List<int>
            {
                    8,7,6,5
            };
            //停止位
            //this.StopBits = new List<string>();

            //获取可用串口号
            string[] ports = System.IO.Ports.SerialPort.GetPortNames();           
            // Display each port name to the console.
            foreach (string port in ports)
            {
                System.Console.WriteLine("当前可用串口号：" + port);
                this.PortName.Add(port);
            }
            //通过反射来获取其他的参数列表
            //校验位 
            this.Parity = SetPortParity((new SerialPort()).Parity);
            //波特率 - 固定
            //数据位 - 固定
            //停止位 - 反射
            this.StopBits = SetPortStopBits((new SerialPort()).StopBits);
        }
        /// <summary>
        /// 获取校验位列表
        /// </summary>
        /// <param name="defaultPortParity">类型输入</param>
        /// <returns></returns>
        public static List<string> SetPortParity(Parity defaultPortParity)
        {
            List<string> list = new List<string>();
            System.Console.WriteLine("Available Parity options:");
            foreach (string s in Enum.GetNames(typeof(Parity)))
            {
                System.Console.WriteLine("   {0}", s);
                list.Add(s);
            }
            return list;
        }
        /// <summary>
        /// 获取停止位列表
        /// </summary>
        /// <param name="defaultPortStopBits">类型输入</param>
        /// <returns></returns>
        public static List<string> SetPortStopBits(StopBits defaultPortStopBits)
        {
            List<string> list = new List<string>();
            System.Console.WriteLine("Available Parity options:");
            foreach (string s in Enum.GetNames(typeof(StopBits)))
            {
                System.Console.WriteLine("   {0}", s);
                list.Add(s);
            }
            return list;
        }
    }
}
